package com.clkj.zhonghui.service.order;

import com.clkj.zhonghui.dao.order.MainOrderMapper;
import com.clkj.zhonghui.dao.order.OrderMapper;
import com.clkj.zhonghui.dao.points.RebatePointsMapper;
import com.clkj.zhonghui.dao.points.RebateRelationsMapper;
import com.clkj.zhonghui.dao.points.RebateSettingsMapper;
import com.clkj.zhonghui.dao.stored.UserStoredDetailMapper;
import com.clkj.zhonghui.dao.stored.UserStoredMapper;
import com.clkj.zhonghui.pojo.common.DateFormatHelper;
import com.clkj.zhonghui.pojo.order.MainOrder;
import com.clkj.zhonghui.pojo.order.Order;
import com.clkj.zhonghui.pojo.points.RebatePoints;
import com.clkj.zhonghui.pojo.points.RebateRelations;
import com.clkj.zhonghui.pojo.points.RebateSettings;
import com.clkj.zhonghui.pojo.stored.UserStored;
import com.clkj.zhonghui.pojo.stored.UserStoredDetail;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.text.DateFormat;
import java.util.*;

/**
 * @author yawang
 * @create 2024/07/11 13:53:04
 **/
@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    private MainOrderMapper mainOrderMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserStoredMapper userStoredMapper;
    @Autowired
    private UserStoredDetailMapper userStoredDetailMapper;
    @Autowired
    private RebateRelationsMapper rebateRelationsMapper;

    @Autowired
    private RebatePointsMapper rebatePointsMapper;

    @Autowired
    private RebateSettingsMapper rebateSettingsMapper;

    private Map map;
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Map addOrder(MainOrder mainOrder) {
        mainOrder.setOrderNumber(String.valueOf(new Date().getTime()));
        mainOrder.setOrderDate(DateFormatHelper.currentTimes());
        mainOrder.setOrderStatus(0);
        if(mainOrder.getRealMoney()==0){
            if(mainOrder.getUsedStored()>0){
                mainOrder.setOrderStatus(1);
            }else{
                mainOrder.setOrderStatus(4);
            }

        }
        mainOrderMapper.insertSelective(mainOrder);
        for (Order order : mainOrder.getOrderList()) {
            order.setOrderNumber(mainOrder.getOrderNumber());
            order.setProductStatus(0);
        }
        orderMapper.insertList(mainOrder.getOrderList());
        map = new HashMap();
        map.put("orderNum",mainOrder.getOrderNumber());
        double rebate = 0.0;
        if(mainOrder.getRealMoney()>0){
            //使用现金支付，需要给上级返利,-1是鸡胚胎首次购买，-2为用券购买
            if(mainOrder.getParentId()!=0&&mainOrder.getParentId()!=-1&&mainOrder.getParentId()!=-2){
                //有上级
                Example example = new Example(UserStored.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("userId",mainOrder.getParentId());
                UserStored userStored = userStoredMapper.selectOneByExample(example);
                if(userStored!=null){
                    if(userStored.getVipGrade()==0){
                        //上极为普通会员
                        rebate = mainOrder.getRealMoney()*0.1;
                    }
                    if(userStored.getVipGrade()==1){
                        rebate = mainOrder.getRealMoney()*0.2;
                    }
                    if(userStored.getVipGrade()==2){
                        rebate = mainOrder.getRealMoney()*0.25;
                    }
                    if(userStored.getVipGrade()==3){
                        rebate = mainOrder.getRealMoney()*0.3;
                    }
                    if(userStored.getVipGrade()==4){
                        rebate = mainOrder.getRealMoney()*0.3;
                    }
                }else{
                    //普通用户
                    rebate = mainOrder.getRealMoney()*0.1;
                }

            }
        }else{
            //储值金购买，减储值金
            UserStoredDetail detail = new UserStoredDetail();
            detail.setUserId(mainOrder.getUserId());
            detail.setShareId(mainOrder.getParentId());
            detail.setStoredMoney(mainOrder.getUsedStored());
            detail.setShareMoney(0.0);
            detail.setOrderNumber(mainOrder.getOrderNumber());
            detail.setStoredFlag(1);
            detail.setDateTime(DateFormatHelper.currentTimes());

            userStoredDetailMapper.insertSelective(detail);
            userStoredMapper.updatePayUser(mainOrder.getUserId(),mainOrder.getUsedStored());
        }

        map.put("rebate",rebate);
        map.put("msg","rebate--我这一单需要给上级的返利");
        return map;
    }

    @Override
    public PageInfo listOrder(Integer userId, Integer shopId, Integer page, Integer size, Integer flag) {
        PageHelper.startPage(page,size);
        Example example = new Example(MainOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("shopId",shopId).andEqualTo("userId",userId);
        if(flag!=-1){
            criteria.andEqualTo("orderStatus",flag);

        }
        example.orderBy("mainId").desc();
        List<MainOrder> mainOrderList =  mainOrderMapper.selectByExample(example);
        for (MainOrder mainOrder : mainOrderList) {
//            example = new Example(Order.class);
//            criteria = example.createCriteria();
//            criteria.andEqualTo("orderNumber",mainOrder.getOrderNumber());
            mainOrder.setOrderList(orderMapper.getOrderList(mainOrder.getOrderNumber()));
        }
        return new PageInfo(mainOrderList);
    }

    @Override
    public PageInfo listAllOrder(Integer shopId, Integer page, Integer size, Integer flag, String type, String value) {
        PageHelper.startPage(page,size);
        Example example = new Example(MainOrder.class);
        Example.Criteria criteria =example.createCriteria();
        criteria.andEqualTo("shopId",shopId);
        if(flag!=-1){
            criteria.andEqualTo("orderStatus",flag);
        }
        if(type.length()>0){
            criteria.andEqualTo(type,value);
        }
        example.orderBy("mainId").desc();
        return new PageInfo(mainOrderMapper.selectByExample(example));
    }

    @Override
    public void sendOrder(String orderNumber, String wuCompany, String wuOrder, String wuCode) {
        Example example = new Example(MainOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderNumber",orderNumber);
        MainOrder mainOrder = new MainOrder();
        mainOrder.setOrderStatus(2);
        mainOrder.setWuCompany(wuCompany);
        mainOrder.setWuOrder(wuOrder);
        mainOrder.setWuCode(wuCode);
        mainOrderMapper.updateByExampleSelective(mainOrder,example);

    }

    @Override
    public List<Order> orderDetail(String orderNumber) {

        return orderMapper.getOrderList(orderNumber);
    }

    @Override
    public void editOrderStatus(Integer mainId, Integer orderStatus) {
        if (mainId == null) {
            return;
        }
        Example example = new Example(MainOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("mainId",mainId);
        MainOrder mainOrder = new MainOrder();
        mainOrder.setOrderStatus(orderStatus);
        mainOrderMapper.updateByExampleSelective(mainOrder,example);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Map addMiniOrder(MainOrder mainOrder) {
        //查询返利规则
        Example example = new Example(RebateSettings.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("delflag", 0);
        RebateSettings rebateSettings = rebateSettingsMapper.selectOneByExample(example);

        mainOrder.setOrderNumber(String.valueOf(new Date().getTime()));
        mainOrder.setOrderDate(DateFormatHelper.currentTimes());
        mainOrder.setOrderStatus(4);
        mainOrderMapper.insertSelective(mainOrder);
        for (Order order : mainOrder.getOrderList()) {
            order.setOrderNumber(mainOrder.getOrderNumber());
            order.setProductStatus(0);
        }
        orderMapper.insertList(mainOrder.getOrderList());
        map = new HashMap();
        map.put("orderNum", mainOrder.getOrderNumber());

        double rebate = 0.0;
        //上级
        RebateRelations rebateRelations = rebateRelationsMapper.listRelations(mainOrder.getParentId());
        if (rebateRelations != null && rebateRelations.getNote() != 0) {
            rebate = mainOrder.getRealMoney() * rebateSettings.getLevelOnePercentage();
        }
        double rebates = 0.0;
        //上上级
        RebateRelations rebateRelationses = rebateRelationsMapper.listRelations(mainOrder.getHighestId());
        if (rebateRelationses != null && rebateRelationses.getNote() != 0) {
            rebates = mainOrder.getRealMoney() * rebateSettings.getLevelTwoPercentage();
        }
        map.put("rebate", rebate);
        map.put("msg", "rebate--我这一单需要给上级返利");
        map.put("rebates", rebates);
        map.put("msg", "rebates--我这一单需要给上上级返利");
        return map;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Map addMiniProductOrder(MainOrder mainOrder) {
        mainOrder.setOrderNumber(String.valueOf(new Date().getTime()));
        mainOrder.setOrderDate(DateFormatHelper.currentTimes());
        mainOrder.setOrderStatus(0);
        if (mainOrder.getRealMoney() == 0) {
            if (mainOrder.getUsedYh() > 0) {
                mainOrder.setOrderStatus(1);
            } else {
                mainOrder.setOrderStatus(4);
            }
        }
        mainOrderMapper.insertSelective(mainOrder);
        for (Order order : mainOrder.getOrderList()) {
            order.setOrderNumber(mainOrder.getOrderNumber());
            order.setProductStatus(0);
        }
        orderMapper.insertList(mainOrder.getOrderList());
        map = new HashMap();
        map.put("orderNum", mainOrder.getOrderNumber());
        Double usedYh =mainOrder.getUsedYh();
        Double usedYh1 =mainOrder.getUsedYh();
        if (mainOrder.getUsedYh() != 0 && mainOrder.getUsedStored()==0) {
            Example example = new Example(RebatePoints.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", mainOrder.getUserId());
            criteria.andIn("pointType", Arrays.asList(1, 3));
            Date currentDate = new Date();
            criteria.andGreaterThan("expiryDate", currentDate);
            example.orderBy("expiryDate").asc();
            List<RebatePoints> rebatePointsList = rebatePointsMapper.selectByExample(example);
            for (RebatePoints rebatePoint : rebatePointsList) {
                if (usedYh >= rebatePoint.getSurplusPoints()) {
                    usedYh -= rebatePoint.getSurplusPoints(); // 更新可用积分数量
                    rebatePoint.setSurplusPoints(0.0);
                    rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                } else if (usedYh > 0 && rebatePoint.getSurplusPoints() > 0) {
                    double originalSurplusPoints = rebatePoint.getSurplusPoints();
                    rebatePoint.setSurplusPoints(originalSurplusPoints - usedYh); // 更新剩余积分券数量
                    usedYh = 0.0;
                    rebatePointsMapper.updateByPrimaryKeySelective(rebatePoint);
                    break; //没有更多的积分可以扣除了
                }
            }
            RebatePoints rebatePoints = new RebatePoints();
            rebatePoints.setUserId(mainOrder.getUserId());
            rebatePoints.setPoints(usedYh1);
            rebatePoints.setOrderNum(mainOrder.getOrderNumber());
            rebatePoints.setEarnedDate(DateFormatHelper.currentTimes());
            rebatePoints.setPointType(0);
            rebatePointsMapper.insertSelective(rebatePoints);
        }
        map.put("msg", "正常的商品订单非购买套餐");
        return map;
    }

}
